<template>
  <section id="app" class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input
        class="new-todo"
        placeholder="What needs to be done?"
        autocomplete="off"
        autofocus
        v-model="input"
        @keyup.enter="addTodo"
        >
    </header>
    <section class="main">
      <input id="toggle-all" v-model="allDone" class="toggle-all" type="checkbox">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <li
          v-for="(todo, index) in filterTodos"
          :key="todo"
          :class="{ editing: todo === editingTodo, completed: todo.completed }"
        >
          <div class="view">
            <input class="toggle" type="checkbox" v-model="todo.completed">
            <label @dblclick="editTodo(todo)">{{ todo.text }}</label>
            <button class="destroy" @click="deleteTodo(index)"></button>
          </div>
          <input
            class="edit"
            type="text"
            v-editing-focus="todo === editingTodo"
            v-model="todo.text"
            @keyup.enter="doneEdit(todo)"
            @blur="doneEdit(todo)"
            @keyup.esc="cancelEdit(todo)"
            >
        </li>
      </ul>
    </section>
    <footer class="footer">
      <span class="todo-count">
        <strong>{{ remainingCount }}</strong>  left
      </span>
      <ul class="filters">
        <li><a href="#/all">All</a></li>
        <li><a href="#/active">Active</a></li>
        <li><a href="#/completed">Completed</a></li>
      </ul>
      <button class="clear-completed">
        Clear completed
      </button>
    </footer>
  </section>
  <footer class="info">
    <p>Double-click to edit a todo</p>
    <!-- Remove the below line ↓ -->
    <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
    <!-- Change this out with your name and url ↓ -->
    <p>Created by <a href="https://www.lagou.com">名木川</a></p>
    <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
  </footer>
</template>

<script>
import './assets/index.css'
import { ref, computed, onMounted, onUnmounted, watchEffect } from 'vue'
import useLocalStorage from './util/useLocalStorage.js'
const storage = useLocalStorage()

//添加待办事项
const useAdd = todos => {
  const input = ref('')
  const addTodo = () => {
    const text = input.value && input.value.trim()
    if(!text.length) return 
    todos.value.unshift({
      text,
      completed: false
    })
    input.value = ""
  }
  return {
    input,
    addTodo
  }
}

//删除待办事项
const useDelete = (todos) => {
  const deleteTodo = (index) => {
    todos.value.splice(index, 1)
  }
  return {
    deleteTodo
  }
}


/**
 * 编译待办事项：
 * 1.双击待办项，展示编辑文本框
 * 2.按回车或者编辑文本框失去焦点，修改数据
 * 3.按esc取消编辑
 * 4.把编辑文本框清空按回车，删除这一项
 * 5.显示编辑文本框的时候获取焦点
 */

 const useEdit = (deleteTodo) => {
   let beforeEditingText = ''  //编辑前此条数据的初始值
   const editingTodo = ref(null)  //编辑的状态，通过有值判断是否相同

   const editTodo = todo => {
     beforeEditingText = todo.text
     editingTodo.value = todo
   }

   const doneEdit = todo => {
    //  console.log(editingTodo.value);
    //  if(!editingTodo.value) return
     todo.text = todo.text.trim()
     todo.text || deleteTodo(todo)
     editingTodo.value = null
   }

   const cancelEdit = todo => {
     editingTodo.value = null
     todo.text = beforeEditingText
   }

   return {
     useEdit,
     editTodo,
     doneEdit,
     cancelEdit,
     editingTodo
   }
 }
 

//切换待办事项状态
const useFilter = todos => {
  const allDone = computed({
    get () {
      return todos.value.every(item => item.completed)
    },
    set (value) {
      todos.value.forEach(todo => {
        todo.completed = value
      })
    }
  })
  const type = ref('all')

  /** BUG 1. TODO! 使用这种方法切换数据有问题 */
  // const filter = {
  //   all: todos.value,
  //   active: todos.value.filter(item => item.completed),
  //   completed: todos.value.filter(item => !item.completed),
  // }
  // const filterTodos = computed(() => filter[type.value])
  // const remainingCount = computed(() => filter.active.length)

  /** 2. TODO! 使用这个可以 */
  const filter = {
    all: list => list,
    active: list => list.filter(todo => todo.completed),
    completed: list => list.filter(todo => !todo.completed)
  }
  const filterTodos = computed(() => filter[type.value](todos.value)) //这样的写法todos数据是实时的
  const remainingCount = computed(() => filter.active(todos.value).length)
  const onHashChange = () => {
    const hash = window.location.hash.replace("#/", '')
    if(filter[hash]) {
      type.value = hash
    }else {
      type.value = 'all'
      window.location.hash = ''
    }
  }




  onMounted(() => {
    window.addEventListener('hashchange', onHashChange)
    onHashChange()  //首次加载执行
  })

  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashChange)
  })


  return {
    allDone,
    filterTodos,
    remainingCount
  }
}


//本地存储
const useStorage = () => {
  let KEY = "TODOKEYS"
  const todos = ref(storage.getItem(KEY) || [])
  watchEffect(() => {
    storage.setItem(KEY, todos.value)
  })
  return todos
}


export default {
  name: "TodoList",
  setup () {
    const todos = useStorage()

    let { deleteTodo } = useDelete(todos)
    return {
      ...useAdd(todos),
      // ...useDelete(todos),
      ...useEdit(deleteTodo),
      ...useFilter(todos),
      deleteTodo,
      todos,
    }
  },
  directives: {
    editingFocus: (el, binding) => {
      binding.value && el.focus()
    }
  }
}
</script>

<style>
</style>
